<?php

namespace app\controller\api;

use app\BaseController;
use app\model\Merchant;
use app\model\MerchantBalance;
use app\model\StationOrder;
use sheng_pay\SPay;
use think\Response;
use yly_print\YlyOpen;

class Order extends BaseController
{
    public function create(): Response
    {
        return $this->success($this->app->make(StationOrder::class)->createOrder());
    }

    public function cancel(): Response
    {
        $data = $this->detail()->getData();
        $data = $data['result'];
        if ($data['state'] != 0) throw new \Exception("订单状态异常");
        (new StationOrder)->where('id', $data['id'])->save(['state' => 6, 'cancel_time' => date("Y-m-d H:i:s")]);
        $data['state'] = 6;
        if ($data['station']['mer_id'] > 0) {
            (new Merchant)->where('id', $data['static']['mer_id'])->dec("disable_balance", $data['merchant_money'])->inc('balance', $data['merchant_money'])->save();
        }
        return $this->success($data);
    }

    public function reload(): Response
    {
        $order = $this->detail()->getData();
        $order = $order['result'];
        if ($order['state'] != 0) throw new \Exception("订单状态异常");
        $payment = $this->app->make(StationOrder::class)->pay($order['order_sn'], $order['money'], $order['pay_id'], $order['station']);
        return $this->success($payment['create']);
    }

    public function detail(): string|Response
    {
        $param = $this->request->param();
        if (empty($param['outTradeNo'])) return "Error";
        $order = (new StationOrder)->with(['station'])->where('order_sn', $param['outTradeNo'])->find();
        if (empty($order)) {
            if (!empty($param['call'])) throw new \Exception("订单不存在");
            return "Error";
        }
        if ($order['state'] != 0) {
            return !empty($param['call']) ? $this->success($order) : "Success";
        }
        //获取支付订单
        $res = $this->app->make(SPay::class)->queryOrder($order['order_sn']);
//        dd($res);
        //订单状态0：待支付 1：已支付 2：已完成 3：申请退款 4：退款中 5：已退款 6：已关闭
        if (in_array(strtoupper($res['status']), ['PAY_FAIL', 'CLOSED'])) {
            $order['state'] = 6;
            $order['cancel_time'] = date("Y-m-d H:i:s");
        } elseif ($res['status'] == 'PAY_SUCCESS') {
            $order['state'] = 1;
            $order['payment_time'] = date("Y-m-d H:i:s");
        } else {
            $create_time = strtotime("+20 min", strtotime($order['create_time']));
            if (time() > $create_time) {
                $order->state = 6;
                $order->close_time = date("Y-m-d H:i:s");
            }
        }
        $order->save();
        $station = $order['station'];
        if (!empty($station['print_sn']) && $order['state'] == 1) {
            //打印订单
            $this->app->make(YlyOpen::class, ['id' => $station['print_sn'], 'token' => $station['print_key']])->printStation($station['print_sn'], [
                "station" => $station['name'],
                "order_sn" => $order['order_sn'],
                "date" => $order->payment_time,
                "gun_name" => $order['gun'],
                "oil_name" => $order['oil'],
                "money" => $order['amount']
            ]);
        }
        //扣减商家余额
        if ($station['mer_id'] > 0) {
            $tot = (new Merchant)->where('id', $station['mer_id'])->find();
            $totOld = bcadd($tot->disable_balance, $tot->balance, 2);
            $tot->dec("disable_balance", $order['merchant_money'])->save();
            $new_money = bcsub($totOld, $order['merchant_money'], 2);
            //余额动账
            (new MerchantBalance)->save([
                "mer_id" => $station['mer_id'],
                "order_sn" => $order['order_sn'],
                "content" => $station['name'] . "油站加油付款",
                "money" => $order['merchant_money'],
                "old_money" => $totOld,
                "new_money" => $new_money,
                "type" => 2,
                "des" => 5
            ]);
        }
        return !empty($param['call']) ? $this->success($order) : "Success";
    }
}
